
using System.Data;
using System;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.Security.Principal;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using SharePoint.ImportExport.Importer;

namespace SharePoint.ImportExport.MigrationSuite
{
    public partial class ImportSettings : LayoutsPageBase
    {
        //// add control fields to match controls tags on .aspx page
        protected Label lblStatus;
        protected Button btnImport;
        protected Button btnBack;
        protected TextBox txtDirName;
        /*
                    <wssuc:InputFormControl LabelText="Import to" runat="server">
                         <Template_Control>
                            <asp:DropDownList ID="drpDestinations" runat="server" AutoPostBack="true" />
                            <asp:DropDownList ID="drpPrefixes" runat="server" AutoPostBack="true"/>
                            <asp:TextBox ID="txtSiteName" runat="server" Enabled="true" height=20 />
                         </Template_Control>
                    </wssuc:InputFormControl>
        -->			

                protected DropDownList drpDestinations;

                protected DropDownList drpPrefixes;
                protected TextBox txtSiteName;
        */
        protected DropDownList drpDirectories;
        protected String returnValue;
        private bool loaded = false;
        private string exportSiteURLFromFile = "";
        private string exportSiteURL = "";
        private bool HasPermissionsOnSite(string siteURL)
        {
            bool returnValue = false;
            try
            {
                SPUser currentUser = SPContext.Current.Web.CurrentUser;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    try
                    {
                        using (Microsoft.SharePoint.SPSite currentSite = new Microsoft.SharePoint.SPSite(siteURL))
                        {
                            using (Microsoft.SharePoint.SPWeb currentWeb = currentSite.OpenWeb())
                            {
                                SPGroup ownersGroup = currentWeb.AssociatedOwnerGroup;

                                ////Check if currentuser belongs to owners group of the current web
                                foreach (SPUser user in ownersGroup.Users)
                                {
                                    if (currentUser.LoginName == user.LoginName)
                                    {
                                        returnValue = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    catch (System.IO.FileNotFoundException fileEx)
                    {
                        returnValue = true;
                    }
                    catch (Exception ex)
                    {
                        //blah blah
                    }
                });

            }
            catch (SPException spEx)
            {
                if (spEx.ErrorCode == 1)
                {
                }
            }
            catch (System.IO.FileNotFoundException fileEx)
            {
                returnValue = true;
            }
            return returnValue;
        }



        void btnImport_Click(Object sender, EventArgs e)
        {
            string newPage = Request.Url.ToString();
            string dirName = txtDirName.Text;
            if (dirName.Trim().Length == 0)
            {
                dirName = drpDirectories.SelectedItem.Text;
            }

            exportSiteURLFromFile = this.Web.Url;
            string webApp = exportSiteURLFromFile.Substring(0, exportSiteURLFromFile.Length - this.Web.ServerRelativeUrl.Length);

            string managedpath = this.Web.Site.ServerRelativeUrl.Substring(1);
            if (managedpath.IndexOf("/") > 0)
            {
                managedpath = managedpath.Substring(0, managedpath.IndexOf("/"));
            }
            else
            {
                managedpath = String.Empty;
            }
            string siteName = this.Web.ServerRelativeUrl.Substring(1);

            if (managedpath.Length > 0)
            {
                siteName = siteName.Substring(managedpath.Length + 1);
            }

            //if (String.IsNullOrEmpty(txtSiteName.Text))
            //{
            //    exportSiteURLFromFile = drpDirectories.SelectedValue;
            //    if (!HasPermissionsOnSite(exportSiteURLFromFile))
            //    {
            //        lblStatus.Text = "You do not have sufficient permissions on site: " + exportSiteURLFromFile + " to perform this operation";
            //        return;
            //    }
            //}
            //else
            //{
            //    exportSiteURLFromFile = drpDestinations.Text + "/" + drpPrefixes.Text + "/" + txtSiteName.Text;

            if (!HasPermissionsOnSite(exportSiteURLFromFile))
            {
                lblStatus.Text = "You do not have sufficient permissions on site: " + exportSiteURLFromFile + " to perform this operation";
                return;
            }
            //}

            using (SPLongOperation operation = new SPLongOperation(this.Page))
            {
                operation.LeadingHTML = "Creating Site";

                operation.TrailingHTML = "Please wait while the site content is being from " + dirName;

                operation.Begin();

                SPUtility.ValidateFormDigest();
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    Importer.ImportWrapper importer = new Importer.ImportWrapper();
                    string logFile = dirName + "\\import - " + DateTime.Now.ToString("yyyyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture) + ".log";
                    importer.Init(false, logFile);

                    string contentDeploymentFiles;
                    try
                    {
                        string result = importer.Process(dirName, webApp, true, true, true, false, managedpath, siteName, out contentDeploymentFiles);
                        if (result.IndexOf("OK: ") == 0)
                        {
                            this.btnBack.Text = "Go";
                            newPage = result.Substring(4);
                            if (newPage.IndexOf("|") > 0)
                            {
                                logFile = newPage.Substring(newPage.IndexOf("|") + 1);
                                newPage = newPage.Substring(0, newPage.IndexOf("|"));
                            }

                            this.btnBack.PostBackUrl = newPage;
                            importer.ImportData(contentDeploymentFiles, dirName, newPage, true);
                            importer.Close();
                            lblStatus.Text = "Site: " + newPage + " created";
                            this.btnBack.Enabled = true;

                            bool listExists = false;
                            Guid listID = Guid.Empty;
                            try
                            {
                                using (Microsoft.SharePoint.SPSite site = new Microsoft.SharePoint.SPSite(this.exportSiteURL))
                                {
                                    using (Microsoft.SharePoint.SPWeb web = site.RootWeb)
                                    {

                                        foreach (Microsoft.SharePoint.SPList list in web.Lists)
                                        {
                                            if (list.Title == "ImportedData")
                                            {
                                                listExists = true;
                                                listID = list.ID;
                                                break;
                                            }

                                        }
                                        if (!listExists)
                                        {
                                            listID = web.Lists.Add("ImportedData", "This contains the import info for the list", SPListTemplateType.GenericList);

                                        }
                                        if (listID != Guid.Empty)
                                        {
                                            Microsoft.SharePoint.SPList list = web.Lists[listID];
                                            Microsoft.SharePoint.SPListItem item = list.Items.Add();
                                            if (!list.Fields.ContainsField("ImportDirectory"))
                                            {
                                                list.Fields.Add("ImportDirectory", SPFieldType.Text, true);
                                                list.Fields.Add("Result", SPFieldType.Text, false);
                                            }

                                            item["Title"] = exportSiteURLFromFile;
                                            item["ImportDirectory"] = dirName;
                                            item.Update();

                                            if (!String.IsNullOrEmpty(logFile))
                                            {
                                                using (FileStream attachmentStream = new FileStream(logFile, FileMode.Open))
                                                {
                                                    if (attachmentStream.Length > 0)
                                                    {
                                                        BinaryReader binaryAttachmentReader = new BinaryReader(attachmentStream);
                                                        byte[] attachmentFileBytes = binaryAttachmentReader.ReadBytes((int)attachmentStream.Length);
                                                        item.Attachments.Add("Results.log", attachmentFileBytes);
                                                    }
                                                }
                                            }
                                            //File.Delete(logFile);
                                            item.Update();
                                            item.BreakRoleInheritance(false);
                                            SPRoleAssignment roleAssignement = new SPRoleAssignment(web.CurrentUser.LoginName, web.CurrentUser.Email, web.CurrentUser.Name, "");
                                            SPRoleDefinition roleDefinition = web.RoleDefinitions["Full Control"];
                                            roleAssignement.RoleDefinitionBindings.Add(roleDefinition);
                                            item.RoleAssignments.Add(roleAssignement);

                                            roleAssignement = new SPRoleAssignment(web.SiteAdministrators[0].LoginName, web.SiteAdministrators[0].Email, web.SiteAdministrators[0].Name, "");
                                            roleAssignement.RoleDefinitionBindings.Add(roleDefinition);
                                            item.RoleAssignments.Add(roleAssignement);
                                            item.Update();

                                            item.Update();
                                        }
                                    }
                                }
                            }
                            catch (SPException spEx)
                            {
                                this.lblStatus.Text = "Error occurred when saving item to site: " + this.exportSiteURL + ". Error: " + spEx.Message;
                            }
                        }

                        else
                        {
                            lblStatus.Text = result;
                        }
                    }
                    catch (Exception Ex)
                    {
                        lblStatus.Text = Ex.StackTrace;
                    }

                });

                operation.End(newPage);
            }
        }

        protected override void OnInitComplete(EventArgs e)
        {
            if (loaded)
            {
                return;
            }

            loaded = true;
            this.btnImport.Click += new EventHandler(this.btnImport_Click);
            if (!String.IsNullOrEmpty(Request.QueryString["Result"]))
            {
                lblStatus.Text = Request.QueryString["Result"];
            }

            ExportLocationService service = ExportLocationService.Local;
            if (service != null)
            {
                foreach (ContentLocation loc in service.Locations)
                {
                    if (loc.DisplayName == "MigrationSuite.Site")
                    {
                        exportSiteURL = loc.Url;
                    }
                }
            }

            //    this.Web.AllowUnsafeUpdates = true;

            //    SPSecurity.RunWithElevatedPrivileges(delegate()
            //    {
            //        try
            //        {
            //            SPWebServiceCollection webServices = new SPWebServiceCollection(SPFarm.Local);

            //            foreach (SPWebService webService in webServices)
            //            {

            //                foreach (SPWebApplication webApp in webService.WebApplications)
            //                {
            //                    bool skip = false;
            //                    if (webApp.IsAdministrationWebApplication)
            //                    {
            //                        skip = true;
            //                    }

            //                    if (webApp.Properties.ContainsKey("Microsoft.Office.Server.SharedResourceProvider"))
            //                    {
            //                        skip = true;
            //                    }

            //                    if (webApp.Sites[0].RootWeb.WebTemplate == "OSRV")
            //                    {
            //                        skip = true;
            //                    }

            //                    if (skip)
            //                    {
            //                        continue;
            //                    }

            //                    foreach (SPAlternateUrl altUrl in webApp.AlternateUrls)
            //                    {
            //                        drpDestinations.Items.Add(altUrl.IncomingUrl);
            //                    }

            //                    SPPrefixCollection prefixCollection = webApp.Prefixes;
            //                    foreach (SPPrefix prefix in prefixCollection)
            //                    {
            //                        drpPrefixes.Items.Add(prefix.Name);
            //                    }
            //                }
            //            }
            //        }
            //        catch (Exception Ex)
            //        {
            //            lblStatus.Text = "Error when reading SharePoint data.";
            //        }
            //    });

            if (drpDirectories.Items.Count == 0)
            {
                try
                {
                    Hashtable ht = new Hashtable();
                    using (Microsoft.SharePoint.SPSite site = new Microsoft.SharePoint.SPSite(exportSiteURL))
                    {
                        using (Microsoft.SharePoint.SPWeb web = site.RootWeb)
                        {
                            Microsoft.SharePoint.SPList list = web.Lists["ExportedData"];
                            foreach (Microsoft.SharePoint.SPListItem item in list.Items)
                            {
                                try
                                {
                                    if (!ht.ContainsKey(item["ExportDirectory"].ToString()))
                                    {
                                        string URL = item["SiteURL"].ToString();
                                        URL = URL.Substring(0, URL.IndexOf(","));
                                        ht.Add(item["ExportDirectory"].ToString(), URL);
                                        ListItem li = new ListItem(item["ExportDirectory"].ToString(), URL);
                                        drpDirectories.Items.Add(li);
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }
                catch (Exception Ex)
                {
                }
            }
        }
    }
}
